package org.ubc.cs410.disposal2020.server;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import org.ubc.cs410.disposal2020.PMF;
import org.ubc.cs410.disposal2020.Robot;
import org.ubc.cs410.disposal2020.client.RobotService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RobotServiceImpl extends RemoteServiceServlet implements
RobotService {
	public void moveRobot(String robotKey, double newLat, double newLng) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();

		try {
			Robot robot = pm.getObjectById(Robot.class, robotKey);
			if (robot!=null) {
				tx.begin();
				// Needed for persistence for some reason, don't change.
				pm.detachCopy(robot.getPlayer().getGame());
				pm.detachCopy(robot.getPlayer());				  
				robot.move(newLat, newLng);
				int collected = robot.getPlayer().getGame().collectGarbage(newLat, newLng, Robot.GARBAGE_COLLECTION_RADIUS);
				robot.getPlayer().addScore(collected);
				tx.commit();
			}
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

	}


}
